#include <omp.h>
#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <stdlib.h>
#include <time.h>
#include <iostream>

using namespace std;



long int summe()
{
    const int N = 1000;

    int d, id;
    long int a[N],b[N];
    #pragma omp parallel for shared (a)
    for (int i=0;i<N;i++)
                    a[i]=i+1;
    d = N;

    do {

        d = d / 2;

        #pragma omp for
        for (int i=0; i<=d-1;i++) { // parallel auf d Prozessoren EREW‐PRAM mittels 2. Array b implementiert
                b[i] = a[2 * i] + a[2 * i + 1];

                if(i=d-1){
                    id = omp_get_thread_num();
                    cout << "thread " << id << " fertig" << endl;
                }

        }

        #pragma omp for
        for (int i=0; i<=d-1;i++) // parallel auf d Prozessoren
             a[i] = b[i];


    } while (d > 1);
    return(a[0]);
}

int main(int argc, char* argv[]) {


    cout << "ergebnis: " << summe() << endl;
/*
    const int N = 100000;
    int d, i,j,n_threads;
    double antwort;
    double a[N]; // sum = 500500  (n(n+1)) / 2
    double comp_start, comp_end;

    printf( "Anzahl der threads=?");
    fflush(stdout);
    scanf("%d", &n_threads);


    omp_set_num_threads(n_threads);
    omp_set_dynamic(0);

    d = N;

    //init
    for(int i=0; i<N; i++) a[i] = i+1;

    comp_start=omp_get_wtime();

    do {
        int odd = d%2;
        d = d / 2;

        #pragma omp paralell for private(i) shared (a)
        for (i=0; i <= d-1; i++){ // parallel auf d Prozessoren
            a[i] = a[2 * i] + a[2 * i + 1];
        }

        if(odd) a[0] += a[d*2+odd-1]; // addiere vorheriges d-1

    } while (d > 1);


    comp_end=omp_get_wtime();
    printf( "\nCPU-time used is: %f\n",(comp_end-comp_start));


    antwort = a[0];
    std::cout << "Summe: " << antwort << endl;
*/
    return 0;

}
